import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import { Table, Button, Space, Tooltip, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { AadTokenProvider } from '@microsoft/sp-http';
import moment from 'moment';
import { fetchTasks } from '../../config/api/project';

const MailList = (props) => {
console.log('MailList props:', props);
const [timeRange, setTimeRange] = useState('past-week');
const [taskData, setTaskData] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);

// 获取任务数据
const fetchTaskList = async () => {
  try {
    setLoading(true);
    
    // 计算时间范围
    const now = moment(); // 使用 moment 对象
    let startDate, endDate;
    
    switch(timeRange) {
      case 'past-week':
        startDate = now.clone().subtract(7, 'days').startOf('day');
        endDate = now.clone().endOf('day');
        break;
      case 'next-two-weeks':
        startDate = now.clone().startOf('day');
        endDate = now.clone().add(14, 'days').endOf('day');
        break;
      case 'next-four-weeks':
        startDate = now.clone().startOf('day');
        endDate = now.clone().add(28, 'days').endOf('day');
        break;
      default:
        startDate = now.clone().startOf('day');
        endDate = now.clone().add(7, 'days').endOf('day');
    }

    const tasks = await fetchTasks(props.context);
    // const mockTasks = [
    //   {
    //     Id: 101,
    //     Title: "完成项目报告",
    //     ProjectId: 1,
    //     StartTime: "2023-12-10 00:00:00",
    //     EndTime: "2023-12-15 00:00:00",
    //     Priority: "高",
    //     Status: "进行中",
    //     Category: "文档",
    //     Notes: "需要收集所有团队成员的反馈",
    //     Created: "2023-12-01 00:00:00",
    //     Modified: "2023-12-05 00:00:00",
    //   },
    //   {
    //     Id: 102,
    //     Title: "安排团队会议",
    //     ProjectId: 1,
    //     StartTime: "2023-12-12 00:00:00",
    //     EndTime: "2023-12-12 00:00:00",
    //     Priority: "中",
    //     Status: "已完成",
    //     Category: "沟通",
    //     Notes: "讨论项目A的下一个里程碑",
    //     Created: "2023-12-08 00:00:00",
    //     Modified: "2023-12-12 00:00:00",
    //   },
    //   {
    //     Id: 103,
    //     Title: "开发新功能模块",
    //     ProjectId: 2,
    //     StartTime: "2024-01-01 00:00:00",
    //     EndTime: "2024-01-10 00:00:00",
    //     Priority: "高",
    //     Status: "未开始",
    //     Category: "开发",
    //     Notes: "根据需求文档实现功能",
    //     Created: "2023-12-20 00:00:00",
    //     Modified: "2023-12-20 00:00:00",
    //   },
    //   {
    //     Id: 104,
    //     Title: "用户界面设计",
    //     ProjectId: 2,
    //     StartTime: "2024-01-05 00:00:00",
    //     EndTime: "2024-01-12 00:00:00",
    //     Priority: "中",
    //     Status: "进行中",
    //     Category: "设计",
    //     Notes: "设计符合用户体验的界面",
    //     Created: "2023-12-25 00:00:00",
    //     Modified: "2024-01-03 00:00:00",
    //   },
    // ];
    // const tasks = mockTasks;
    
    // 过滤在时间范围内的任务
    const filteredTasks = tasks.filter(task => {
      const taskStartTime = moment(task.StartTime);
      const taskEndTime = moment(task.EndTime);
      // 确保比较是基于整个天的范围
      return taskStartTime.isSameOrBefore(endDate, 'day') && taskEndTime.isSameOrAfter(startDate, 'day');
    });

    // 格式化数据
    const formattedData = filteredTasks.map((task, index) => ({
      key: task.Id,
      id: index + 1,
      title: task.Title,
      startTime: moment(task.StartTime).format('M月D日 (周)'),
      endTime: moment(task.EndTime).format('M月D日 (周)'),
      priority: task.Priority,
      status: {
        text: task.Status,
        type: getStatusType(task.Status)
      },
      category: task.Category,
      notes: task.Notes
    }));

    setTaskData(formattedData);
  } catch (error) {
    console.error('获取任务数据失败:', error);
    message.error('获取任务数据失败，请稍后重试');
  } finally {
    setLoading(false);
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '已完成':
      return 'success';
    case '进行中':
      return 'warning';
    case '未开始':
      return 'error';
    default:
      return 'warning';
  }
};

// 监听时间范围变化
useEffect(() => {
  if (props.context) {
    fetchTaskList();
  }
}, [timeRange, props.context]);

// 获取任务数量
const getTaskCount = () => {
  return taskData.length;
};

// 获取忙碌状态
const getBusyStatus = () => {
  const count = getTaskCount();
  if (count > 10) {
    return {
      status: '忙碌',
      emoji: '😢',
      description: '(任务数量超过10个，非常忙碌)'
    };
  } else if (count > 5) {
    return {
      status: '适中',
      emoji: '😐',
      description: '(任务数量在5-10个之间，适中)'
    };
  } else {
    return {
      status: '轻松',
      emoji: '😀',
      description: '(任务数量少于5个，比较轻松)'
    };
  }
};

// 表格列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
    width: '5%',
  },
  {
    title: '待办事项名称',
    dataIndex: 'title',
    key: 'title',
    width: '20%',
    ellipsis: {
      showTitle: false,
    },
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: '15%',
  },
  {
    title: '截止时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: '15%',
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: '8%',
  },
  {
    title: '完成状态',
    dataIndex: 'status',
    key: 'status',
    width: '10%',
    render: (status) => (
      <span className={`status-${status.type}`}>
        {status.text}
      </span>
    ),
  },
  {
    title: '分类标签',
    dataIndex: 'category',
    key: 'category',
    width: '10%',
  },
  {
    title: '备注信息',
    dataIndex: 'notes',
    key: 'notes',
    width: '15%',
    ellipsis: {
      showTitle: false,
    },
  },
];

// 设置行样式为偶数行浅蓝色背景
const getRowClassName = (record, index) => {
  return index % 2 === 1 ? 'light-blue-row' : '';
};

const busyStatus = getBusyStatus();

return (
  <div className="calendar-container">
    <div className="header-section">
      <h2 className="page-title">周务列要</h2>
      <p className="task-info">
        您未来一周有 <span className="stat-number">{getTaskCount()}</span> 个任务
      </p>
      <p className="description">
        按时完成哦！加油！
      </p>
      
      <div className="button-container">
        <Space>
          <Button 
            type={timeRange === 'past-week' ? 'primary' : 'default'} 
            ghost={timeRange === 'past-week'}
            onClick={() => setTimeRange('past-week')}
          >
            过去一周
          </Button>
          <Button 
            type={timeRange === 'next-two-weeks' ? 'primary' : 'default'} 
            ghost={timeRange === 'next-two-weeks'}
            onClick={() => setTimeRange('next-two-weeks')}
          >
            未来两周
          </Button>
          <Button 
            type={timeRange === 'next-four-weeks' ? 'primary' : 'default'} 
            ghost={timeRange === 'next-four-weeks'}
            onClick={() => setTimeRange('next-four-weeks')}
          >
            未来四周
          </Button>
        </Space>
      </div>
    </div>
    
    <Table
      dataSource={taskData}
      columns={columns}
      pagination={{
        current: currentPage,
        pageSize: pageSize,
        total: taskData.length,
        showSizeChanger: true,
        showQuickJumper: true,
        position: ['bottomRight'],
      }}
      onChange={(pagination) => {
        setCurrentPage(pagination.current);
        setPageSize(pagination.pageSize);
      }}
      rowClassName={getRowClassName}
      className="table-container"
      scroll={{ x: true }}
      loading={loading}
    />

    <style jsx="true">
      {`
        .calendar-container {
          padding: 20px;
        }
        .light-blue-row {
          background-color: #f0f8ff;
        }
        .ant-table-tbody > tr.light-blue-row:hover > td {
          background-color: #e6f4ff;
        }
        .page-title {
          margin: 0 0 10px 0;
          font-size: 24px;
          font-weight: bold;
        }
        .task-info {
          margin: 10px 0;
          font-size: 16px;
          color: #666;
        }
        .description {
          color: #666;
          margin: 5px 0 15px 0;
          font-size: 14px;
        }
        .button-container {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 15px;
        }
        .stat-number {
          color: #1890ff;
          font-weight: bold;
          font-size: 18px;
        }
        .header-section {
          margin-bottom: 20px;
        }
        .status-success {
          color: #52c41a;
        }
        .status-warning {
          color: #fa8c16;
        }
        .status-error {
          color: #f5222d;
        }
        .table-container {
          background-color: #fff;
          width: 100%;
        }
        .ant-table-container {
          width: 100%;
        }
        .ant-table {
          width: 100%;
        }
        .ant-table-cell {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .ant-table-wrapper {
          width: 100%;
        }
      `}
    </style>
  </div>
);
};

export default MailList;
